﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace Bule.Malbilden.Data
{
    public class Repository<T> : IRepository<T>
    {
        protected ISession session;
        bool isSessionPrivate;

        public Repository()
        {
            session = SessionFactorySingleton.OpenSession();
            isSessionPrivate = true;
        }

        public Repository(ISession session)
        {
            this.session = session;
        }

        ~Repository()
        {
            Dispose();
        }
        
        public ISession Session { get { return session; } }

        public void Add(T T)
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(T);
                transaction.Commit();
            }
        }

        public void Update(T T)
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Update(T);
                transaction.Commit();
            }
        }

        public void Remove(T T)
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(T);
                transaction.Commit();
            }
        }

        public T Get(int id)
        {
            return session.Get<T>(id);
        }

        public ICollection<T> GetAll()
        {
            return session.CreateCriteria(typeof(T)).List<T>();
        }

        public void Dispose()
        {
            if (isSessionPrivate)
                session.Dispose();
        }
    }
}
